package cup.modules.auth.endpoint;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.wf.captcha.SpecCaptcha;
import cup.common.cache.CacheNames;
import cup.common.config.MySystemProperties;
import cup.core.log.exception.ServiceException;
import cup.core.secure.annotation.PreAuth;
import cup.core.tool.api.R;
import cup.core.tool.constant.RoleConstant;
import cup.core.tool.utils.DigestUtil;
import cup.cqzj.auth.service.TokenGranterUtil;

import cup.modules.auth.provider.ITokenGranter;
import cup.modules.auth.provider.TokenGranterBuilder;
import cup.modules.auth.provider.TokenParameter;
import cup.modules.auth.utils.PasswordUtil;
import cup.modules.system.entity.Pass;
import cup.modules.system.entity.User;
import cup.modules.system.service.IPassService;
import cup.modules.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import cup.core.cache.utils.CacheUtil;
import cup.core.jwt.JwtUtil;
import cup.core.jwt.props.JwtProperties;
import cup.core.launch.constant.AppConstant;
import cup.core.launch.constant.TokenConstant;
import cup.core.log.annotation.ApiLog;
import cup.core.redis.cache.CupRedis;
import cup.core.secure.CupUser;
import cup.core.secure.utils.AuthUtil;
import cup.core.tenant.annotation.NonDS;
import cup.core.tool.support.Kv;
import cup.core.tool.utils.Func;
import cup.core.tool.utils.WebUtil;
import cup.modules.auth.utils.TokenUtil;
import cup.modules.system.entity.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static cup.core.cache.constant.CacheConstant.*;

/**
 * 令牌端点
 *
 * @author
 */
@NonDS
@ApiSort(1)
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "用户授权认证", tags = "授权接口")
public class CupTokenEndPoint {

	private final CupRedis cupRedis;
	private final JwtProperties jwtProperties;

	private final MySystemProperties mySystemProperties;
	private final IUserService userService;
	private final IPassService iPassService;
	private final TokenGranterUtil tokenGranterUtil;

	@ApiLog("登录用户验证")
	@PostMapping("/oauth/token")
	@ApiOperation(value = "获取认证令牌", notes = "传入租户ID:tenantId,账号:account,密码:password")
	public Kv token(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId,
					@ApiParam(value = "账号", required = true) @RequestParam(required = false) String username,
					@ApiParam(value = "密码", required = true) @RequestParam(required = false) String password,
//					@ApiParam(value = "部门id,一网通用户第一次进入则", required = false) @RequestParam(required = false) String deptId,
					@ApiParam(value = "经度", required = false) @RequestParam(required = false) String longitude,
					@ApiParam(value = "纬度", required = false) @RequestParam(required = false) String latitude,
					@ApiParam(value = "验证码key", required = false) @RequestParam(required = false) String key,
					@ApiParam(value = "验证码code", required = false) @RequestParam(required = false) String code) {

		//是否开启验证码
		if (mySystemProperties.isEnableAuthCode() && !"-123".equals(key)) {
			if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) {
				throw new ServiceException("请输入验证码");
			}
			String cacheKey = CacheNames.CAPTCHA_KEY + key;
			//获取缓存
			String realCode = cupRedis.get(cacheKey);
			if (StringUtils.isBlank(realCode)) {
				throw new ServiceException("验证码已过期");
			}
			//是否相等
			if (!realCode.equalsIgnoreCase(code) && !code.equals("-123")) {
				throw new ServiceException("验证码输入错误");
			}
			//删除缓存
			cupRedis.del(cacheKey);
		}

		Kv authInfo = Kv.create();

		String grantType = WebUtil.getRequest().getParameter("grant_type");
		String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

		String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs()
					  .set("tenantId", tenantId)
					  .set("username", username)
					  .set("password", password)
					  .set("grantType", grantType)
					  .set("refreshToken", refreshToken)
					  .set("userType", userType);

		ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		//是否一网通办用户第一次进入 如果是则进行初始化进行初始化工作
//		if (null == userInfo && cqzjLoginService.checkIsExistByEpoint(tenantId, username, password)) {
//			//如果用户存在一网通且没有在我们系统中且没有传入部门id 则提示需要部门id
//			if (StringUtils.isBlank(deptId)) {
//				return authInfo.set("error_code", HttpServletResponse.SC_SERVICE_UNAVAILABLE).set("error_description", "一网通用户第一次登录需要选择所属区域");
//			}
//			String msg = cqzjLoginService.initEpointUser(tenantId, username, password, deptId);
//			if (StringUtils.isNotBlank(msg)) {
//				return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", msg);
//			}
//			//重试获取用户信息
//			userInfo = granter.grant(tokenParameter);
//		}

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
		}

		if (userInfo.getUser().getStatus().equals(-1) ||
			Integer.valueOf(2).equals(userInfo.getUser().getIsActivity())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "请联系管理员:关联区域绑定角色激活账号后再次登录!");
		}

		if (Func.isEmpty(userInfo.getUser().getDeptId())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "请关联区域后再登录!");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "请绑定角色后再登录!");
		}

		//如果登录成功 也传入了经纬度 则保存最新用户经纬度信息
		if (StringUtils.isNotBlank(longitude) && StringUtils.isNotBlank(latitude)) {
//			userLogsService.saveUserLocation(userInfo.getUser().getId(), longitude, latitude);
		}
		tokenGranterUtil.generateDeptAndPostName(userInfo);
		return TokenUtil.createAuthInfo(userInfo);
	}

	@ApiLog("刷新token")
	@PostMapping("/oauth/refresh")
	@ApiOperation(value = "刷新token", notes = "刷新token")
	public Kv token(@ApiParam(value = "租户ID", required = true) @RequestParam String tenantId) {

		Kv authInfo = Kv.create();

		String grantType = WebUtil.getRequest().getParameter("grant_type");
		String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

		String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

		TokenParameter tokenParameter = new TokenParameter();
		tokenParameter.getArgs().set("tenantId", tenantId).set("grantType", grantType).set("refreshToken", refreshToken).set("userType", userType);

		ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
		UserInfo userInfo = granter.grant(tokenParameter);

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获取到用户信息");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
		}
		tokenGranterUtil.generateDeptAndPostName(userInfo);
		return TokenUtil.createAuthInfo(userInfo);
	}


	@GetMapping("/oauth/logout")
	@ApiOperation(value = "退出登录")
	public Kv logout() {
		CupUser user = AuthUtil.getUser();
		if (user != null && jwtProperties.getState()) {
			String token = JwtUtil.getToken(WebUtil.getRequest().getHeader(TokenConstant.HEADER));
			JwtUtil.removeAccessToken(user.getTenantId(), String.valueOf(user.getUserId()), token);
		}
		return Kv.create().set("success", "true").set("msg", "success");
	}

	@GetMapping("/oauth/captcha")
	@ApiOperation(value = "获取验证码")
	public Kv captcha() {
		SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
		String verCode = specCaptcha.text().toLowerCase();
		String key = UUID.randomUUID().toString();
		// 存入redis并设置过期时间为5分钟
		cupRedis.setEx(CacheNames.CAPTCHA_KEY + key, verCode, Duration.ofMinutes(5));
		// 将key和base64返回给前端
		return Kv.create().set("key", key).set("image", specCaptcha.toBase64());
	}

	@GetMapping("/oauth/clear-cache")
	@ApiOperation(value = "清除缓存")
	public Kv clearCache() {
		cupRedis.del(CacheUtil.formatCacheName(BIZ_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(USER_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(DICT_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(FLOW_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(SYS_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(PARAM_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(RESOURCE_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(MENU_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(BIZ_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(USER_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(DICT_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(FLOW_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(SYS_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(PARAM_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(RESOURCE_CACHE, false) + "*");
		cupRedis.del(CacheUtil.formatCacheName(MENU_CACHE, false) + "*");
		return Kv.create().set("success", "true").set("msg", "success");
	}

	@GetMapping("/oauth/refresh")
	@ApiOperation(value = "慎点 刷新所有密码 慎点!!!!")
	@Transactional(rollbackFor = Exception.class)
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R refreshUserPassword() {
		List<User> list = userService.list(new QueryWrapper<User>()
											   .eq("status", 1)
											   .eq("is_deleted", 0)
//											   .ne("account","admin")
//											   .eq("account","S1")
		);
		if (CollectionUtils.isEmpty(list)) {
			return R.status(true);
		}

		List<Pass> result = new ArrayList<>();
		Date now = new Date();
		for (User user : list) {
			String pass = PasswordUtil.randomPassword();
			String hex = DigestUtil.hex(SecureUtil.md5(pass));
			user.setPassword(hex);
			Pass pas = new Pass();
			pas.setAccount(user.getAccount());
			pas.setPass(pass);
			pas.setCreateTime(now);
			result.add(pas);
		}

		userService.updateBatchById(list);
		iPassService.saveBatch(result);

		return R.status(true);

	}
}
